import axios from 'axios'
import lodash from 'lodash'
import { message } from '@/utils/util.message'
import qs from 'qs'
import Nprogress from 'nprogress'

function createService() {
  const service = axios.create()
  service.interceptors.request.use(
    config => {
      if (config.method === 'get') {
        config.paramsSerializer = function(params) {
          return qs.stringify(params, { arrayFormat: 'repeat' })
        }
      }
      Nprogress.start()
      return config
    },
    err => Promise.reject(err)
  )
  // 返回对象为json = {code,data,msg}
  service.interceptors.response.use(
    res => {
      const reqData = res.data
      const { code } = reqData
      if (code === undefined) {
        // 如果没有code，可能是非restful接口，如附件下载等
        if (res.request.responseType === 'blob') {
          return reqData
        } else {
          createError('无效返回值')
        }
      } else {
        switch (code) {
          // 默认成功状态码为 1
          case 1: return reqData.data
          // 不是正确的code,默认通知错误信息
          default:
            createError(reqData.msg)
        }
      }
      Nprogress.done()
    },
    err => {
      if (err && err.response) {
        switch (err.response.status) {
          case 400: err.message = '请求错误'; break
          case 401: err.message = '未授权，请登录'; break
          case 403: err.message = '拒绝访问'; break
          case 404: err.message = `请求地址出错: ${err.response.config.url}`; break
          case 408: err.message = '请求超时'; break
          case 500: err.message = '服务器内部错误'; break
          case 501: err.message = '服务未实现'; break
          case 502: err.message = '网关错误'; break
          case 503: err.message = '服务不可用'; break
          case 504: err.message = '网关超时'; break
          case 505: err.message = 'HTTP版本不受支持'; break
          default: break
        }
      }
      createError(err.message)
      Nprogress.done()
      return Promise.reject(err)
    }
  )
  return service
}

function createError(msg) {
  const err = new Error(msg)
  message({
    message: msg,
    type: 'error'
  })
  throw err
}

function createRequestFunction (service) {
  return function (config) {
    // TODO 从cookies读取token
    const token = ''
    const configDefault = {
      headers: {
        'X-Authorization-Token': token,
        'Content-Type': lodash.get(config, 'headers.Content-Type', 'application/json')
      },
      timeout: process.env.VITE_APP_TIMEOUT,
      baseURL: process.env.VITE_APP_API,
      data: {}
    }
    return service(Object.assign(configDefault, config))
  }
}
const service = createService()
export const request = createRequestFunction(service)
export const get = (url, data) => {
  return request({
    url: url,
    method: 'get',
    params: data
  })
}
export const post = (url, data) => {
  return request({
    url: url,
    method: 'post',
    data
  })
}
export const getForFile = (url, data) => {
  return request({
    responseType: 'blob',
    url: url,
    method: 'get',
    params: data
  })
}
export const postForFile = (url, data) => {
  return request({
    responseType: 'blob',
    url: url,
    method: 'post',
    data
  })
}
